package com.quanling.swing.moju.listeners;


import cn.hutool.core.util.StrUtil;
import com.quanling.swing.moju.Constants;
import com.quanling.swing.moju.MainFrame;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Title: UploadButtonListener.java
 * @Description: 上传按钮点击事件
 * @Author: Eric.Tong
 * @Date: 2019/9/12
 */
public class GenerateButtonListener implements ActionListener {

    private MainFrame mainFrame;

    private String bracketsReg;
    private Pattern pattern1;
    private Pattern pattern2;
    private Pattern L122Pattern;
    private Pattern pattern3;
    private Pattern pattern4;
    private Pattern pattern5;
    private Pattern patternF;
    private Pattern patternA;

    public GenerateButtonListener(MainFrame mainFrame) {
        this.mainFrame = mainFrame;
        bracketsReg = "\\([\\S|\\s]*\\)";
        pattern1 = Pattern.compile("G40|D0|G71|G997|N14|N16|N19|N998|N999|FL122");
        pattern2 = Pattern.compile("G93|N9999|N9998");
        L122Pattern = Pattern.compile("L122=\\d+(\\.\\d*)?");
        pattern3 = Pattern.compile("X\\d+(\\.\\d*)?");
        pattern4 = Pattern.compile("C-\\d+(\\.\\d*)?");
        pattern5 = Pattern.compile("A\\d+(\\.\\d*)?");
        patternF = Pattern.compile("F\\d+(\\.\\d*)?");
        patternA = Pattern.compile("A(-*)\\d+(\\.\\d{8})");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (StrUtil.isEmpty(mainFrame.getInputFile().getText())) {
            //如果没有选中输出文件夹
            JOptionPane.showMessageDialog(
                    mainFrame.getFrame(),
                    "请选择输出文件路径",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE
            );
            mainFrame.getInputFile().requestFocus();
            return;
        }
        File file = new File(mainFrame.getInputFile().getText());
        if (StrUtil.isEmpty(mainFrame.getOutputFile().getText())) {
            //如果没有选中输出文件夹
            JOptionPane.showMessageDialog(
                    mainFrame.getFrame(),
                    "请选择输出文件路径",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE
            );
            mainFrame.getOutputFile().requestFocus();
            return;
        }

        String fileNamePath = mainFrame.getOutputFile().getText() + Constants.OUTPUT_FILE_NAME;
        InputStreamReader isr = null;
        BufferedReader reader = null;
        OutputStreamWriter osw = null;
        FileOutputStream fos = null;
        try {
            isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
            reader = new BufferedReader(isr);
            fos = new FileOutputStream(fileNamePath);
            osw = new OutputStreamWriter(fos, "UTF-8");
            StringBuffer sb = new StringBuffer();
            sb.append("%@MACRO\n" +
                    "G90G59G00Z0;\n" +
                    "G90G59G00X0Y0A0C0;\n" +
                    "M03S3000M08M17;\n");
            String readStr;
            String aStr = "";
            BigDecimal totalNumber = new BigDecimal("360");
            BigDecimal sixteenNum = new BigDecimal("16");
            while ((readStr = reader.readLine()) != null) {
                readStr = readStr.replaceAll("L131", "@1");
                readStr = readStr.replaceAll(bracketsReg, "");
                readStr = readStr.replace(" ", "");
                // 1.4
                Matcher matcher1 = pattern1.matcher(readStr);
                if (matcher1.matches()) {
                    readStr = readStr.replace(matcher1.group(), "");
                }
                Matcher matcher2 = pattern2.matcher(readStr);
                if (matcher2.find()) {
                    readStr = readStr.replace(matcher2.group(), "");
                }
                // 把以E开头行删掉
                if (readStr.startsWith("E")) {
                    continue;
                }
                readStr = readStr.replaceAll("\\[NR_SDZ\\]=", "M03S");
                if (readStr.contains("G52")) {
                    String tempStr = readStr.substring(0, readStr.indexOf("ZL115"));
                    readStr = tempStr + readStr.replaceAll("[\\s|\\S]*ZL115", "Z0");
                    // 有G52的整行后面的数都改成0
                    String tempSub = readStr.substring(0, readStr.indexOf("G52") + 4);
                    String endStr = readStr.substring(readStr.lastIndexOf("Z0"));
                    readStr = tempSub + "00" + endStr;
                }
                readStr = readStr.replace("L13=", "F");
                readStr = readStr.replace("F122=", "F");
                // 有G59、L115=、FL124、L146、L150、L151、L155、L156、L162、L163、L164、L165、L922、L923、L924、L925、$、[、T、ENDV这一行都删掉
                if (readStr.indexOf("G59") > -1 ||
                        readStr.indexOf("L115=") > -1 ||
                        readStr.indexOf("FL124") > -1 ||
                        readStr.indexOf("L146") > -1 ||
                        readStr.indexOf("L150") > -1 ||
                        readStr.indexOf("L151") > -1 ||
                        readStr.indexOf("L155") > -1 ||
                        readStr.indexOf("L156") > -1 ||
                        readStr.indexOf("L162") > -1 ||
                        readStr.indexOf("L163") > -1 ||
                        readStr.indexOf("L164") > -1 ||
                        readStr.indexOf("L165") > -1 ||
                        // readStr.indexOf("L922") > -1 ||
                        readStr.indexOf("L923") > -1 ||
                        readStr.indexOf("L924") > -1 ||
                        readStr.indexOf("L925") > -1 ||
                        readStr.indexOf("$") > -1 ||
                        readStr.indexOf("[") > -1 ||
                        readStr.indexOf("T") > -1 ||
                        readStr.indexOf("ENDV") > -1) {
                    continue;
                }
                readStr = readStr.replace("@1G0", "@1G90G0");
                if (readStr.contains("G54")) {
                    readStr = "G58G94G00";
                }
                // FL122开头的行，整行都删掉
                if (readStr.startsWith("FL122")) {
                    continue;
                }
                // 不是FL122开头的行，里面有FL122改成;
                if (readStr.indexOf("FL122") > -1) {
                    readStr = readStr.replaceAll("FL122", "");
                }
                readStr = readStr.replace("G52", "G59G90G00");
                // 7.3：出现L110=后面一直到这一行出现最后一个G，它们之间的都删掉，如果没出现G那就到行末都删掉
                if (readStr.contains("L110=")) {
                    if (readStr.contains("G")) {
                        int startIndex = readStr.indexOf("L110=");
                        int endIndex = readStr.lastIndexOf("G");
                        String subStr;
                        if (endIndex < startIndex) {
                            subStr = readStr.substring(startIndex);
                        } else {
                            subStr = readStr.substring(startIndex, endIndex);
                        }
                        readStr = readStr.replace(subStr, "");
                    } else {
                        readStr = "";
                    }
                }
                //7.4：出现L135=后面一直到这一行出现最后一个G，它们之间的都删掉，如果没出现G那就到行末都删掉
                if (readStr.contains("L135=")) {
                    if (readStr.contains("G")) {
                        int startIndex = readStr.indexOf("L135=");
                        int endIndex = readStr.lastIndexOf("G");
                        String subStr;
                        if (endIndex < startIndex) {
                            subStr = readStr.substring(startIndex);
                        } else {
                            subStr = readStr.substring(startIndex, endIndex);
                        }
                        readStr = readStr.replace(subStr, "");
                    } else {
                        readStr = "";
                    }
                }
                // 7.6 出现L9=数字都删掉
                readStr = readStr.replaceAll("L9=\\d", "");
                // 出现L122=后面一直到这一行出现最后一个G，它们之间的都删掉，如果没出现G那就都不用删掉
                if (readStr.contains("L122=")) {
                    if (readStr.contains("G")) {
                        int startIndex = readStr.indexOf("L122=");
                        int endIndex = readStr.lastIndexOf("G");
                        if (endIndex > startIndex) {
                            readStr = readStr.replace(readStr.substring(startIndex, endIndex), "");
                        }
                    }
                }
                Matcher F122Matcher = L122Pattern.matcher(readStr);
                if (F122Matcher.find()) {
                    readStr = readStr.replace(F122Matcher.group(), "");
                }
                // L122=改成F
                Matcher matcherL122 = L122Pattern.matcher(readStr);
                if(matcherL122.find()) {
                    readStr = readStr.replaceAll(matcherL122.group(), "");
                }
                readStr = readStr.replaceAll("L122=", "F");
                // 7.7 Y与Z对调
                readStr = readStr.replaceAll("Z", "~");
                readStr = readStr.replaceAll("Y", "Z");
                readStr = readStr.replaceAll("~", "Y");
                // 7.8 W改成C-
                readStr = readStr.replace("W", "C-");
                //出现L122后面一直到这一行出现最后一个G，它们之间的都删掉，如果没出现G那就不用删掉
                if (readStr.contains("L122")) {
                    if (readStr.contains("G")) {
                        int startIndex = readStr.indexOf("L122");
                        int endIndex = readStr.lastIndexOf("G");
                        String subStr;
                        if (endIndex < startIndex) {
                            subStr = readStr.substring(startIndex);
                        } else {
                            subStr = readStr.substring(startIndex, endIndex);
                        }
                        readStr = readStr.replace(subStr, "");
                    }
                }
                // 11.0
                readStr = readStr.replace("ZL143", "Z#31");
                readStr = readStr.replace("YL144", "Y#32");
                readStr = readStr.replace("XL145", "X#30");
                readStr = readStr.replace("C-L922", "C-#35");
                readStr = readStr.replace("X", "X-");
                // 15.0，换行处理
                readStr = readStr.replace("Z=", "#31:=");
                readStr = readStr.replace("Y=", "#32:=");
                readStr = readStr.replace("X-=", "#30:=");
                readStr = readStr.replace("C-=", "#35:=");
                readStr = readStr.replaceAll("A=[\\s|\\S]*", "G58G94G00");
                // 换行处理
                if (readStr.contains("#31:=") && readStr.contains("#32:=")
                        && readStr.contains("#30:=") && readStr.contains("#35:=")
                        && readStr.contains("G58G94G00")) {
                    StringBuffer finalStr = new StringBuffer();
                    String sub1 = readStr.substring(readStr.indexOf("#31"), readStr.indexOf("#32")) + ";\n";
                    String sub2 = readStr.substring(readStr.indexOf("#32"), readStr.indexOf("#30")) + ";\n";
                    String sub3 = readStr.substring(readStr.indexOf("#30"), readStr.indexOf("#35")) + ";\n";
                    String sub4 = readStr.substring(readStr.indexOf("#35"), readStr.indexOf("G58G94G00")) + ";\n";
                    String sub5 = readStr.substring(readStr.indexOf("G58G94G00"));
                    finalStr.append(sub1);
                    finalStr.append(sub2);
                    finalStr.append(sub3);
                    finalStr.append(sub4);
                    finalStr.append(sub5);
                    readStr = finalStr.toString();
                }
                // 有--的删掉
                readStr = readStr.replace("--", "");
                // 问题2处理：
                if (readStr.contains("G59G90G00Z00Y0")) {
                    Matcher matcher3 = pattern3.matcher(readStr);
                    if (matcher3.find()) {
                        readStr = readStr.replace(matcher3.group(), "X-00");
                    }
                    Matcher matcher4 = pattern4.matcher(readStr);
                    if (matcher4.find()) {
                        readStr = readStr.replace(matcher4.group(), "C-0");
                    }
                    Matcher matcher5 = pattern5.matcher(readStr);
                    if (matcher5.find()) {
                        readStr = readStr.replace(matcher5.group(), "A0");
                    }
                }
                readStr = readStr.replace("M2", "G59X0Y0Z0A0C90.0;\nG59.2X0Y0Z0A0C90.0;\nM18M30");
                // F后面数字带小数点的把其改成整数，且要把小数点去掉
                Matcher matcherF = patternF.matcher(readStr);
                if(matcherF.find()) {
                    String findStr = readStr.substring(matcherF.group().indexOf("."), matcherF.group().length());
                    readStr = readStr.replace(findStr, "");
                }
//                // 一行里有A
//                Matcher matcherA = patternA.matcher(readStr);
//                if(matcherA.find()) {
//                    // 只处理8位小数的a
//                    String decimalCount = matcherA.group().substring(matcherA.group().indexOf(".") + 1);
//                    if(decimalCount.length() != 8 && StrUtil.isNotBlank(aStr)) {
//                        aStr = "";
//                        return;
//                    }
//                    if(StrUtil.isBlank(aStr)) {
//                        aStr = matcherA.group();
//                    }else {
//                        String compare1 = aStr.substring(aStr.indexOf("A") + 1, aStr.indexOf("A") + 2);
//                        String compare2 = matcherA.group().substring(aStr.indexOf("A") + 1, aStr.indexOf("A") + 2);
//                        if(!compare1.equals(compare2)) {
//                            BigDecimal preNumber = new BigDecimal(aStr.substring(aStr.indexOf(compare1) + 1));
//                            BigDecimal nowNumber = new BigDecimal(matcherA.group().substring(matcherA.group().indexOf(compare2) + 1));
//                            BigDecimal resultNumber;
//                            // 上一行是负数
//                            if("-".equals(compare1)) {
//                                resultNumber = nowNumber.subtract(totalNumber);
//                            } else {
//                                resultNumber = totalNumber.subtract(nowNumber);
//                            }
//                            BigDecimal exeNumber = resultNumber.subtract(preNumber).abs().subtract(sixteenNum);
//                            if(exeNumber.doubleValue() < 0){
//                                readStr = readStr.replace(matcherA.group(), "A" + resultNumber.toString());
//                            }else {
//                                aStr = matcherA.group();
//                            }
//
//                        }else {
//                            // 同极不变，但需要覆盖上一行的值
//                            aStr = matcherA.group();
//                        }
//                    }
//                // 防止隔行匹配
//                }else {
//                    if(StrUtil.isNotBlank(aStr)) {
//                        aStr = "";
//                    }
//                }
                if (StrUtil.isNotBlank(readStr)) {
                    sb.append(readStr + ";\n");
                }
            }
            // 删除空行
            System.out.print(sb.toString());
            osw.write(sb.toString());
            reader.close();
            isr.close();
            osw.close();
            fos.close();
            //如果没有选中输出文件夹
            JOptionPane.showMessageDialog(
                    mainFrame.getFrame(),
                    "生成成功!",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE
            );
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }


}
